package com.linxiao.call.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.linxiao.call.service.ICrmWebCallService;
import com.linxiao.call.vo.CrmWebCallVO;
import com.ruoyi.common.constant.CrmConstants;
import com.ruoyi.common.constant.RedisKeyConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.SysDeptToken;
import com.ruoyi.system.mapper.SysDeptTokenMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 * 语音通知Service
 *
 * @Author qiqi
 * @Date 2022/6/7 16:26
 * @Version 1.0
 */
@Service
public class ICrmWebCallServiceImpl implements ICrmWebCallService {
    private static final Logger log = LoggerFactory.getLogger(ICrmWebCallServiceImpl.class);
    @Value("${tr.call.records.region:null}")
    private String region;
    @Value("${tr.call.records.version:null}")
    private String version;
    // 天润语音通知限制次数
    @Value("${tr.webcall.limit.count:null}")
    private String webcallLimitCount;
    // 天润语音 重试次数
    @Value("${tr.webcall.retry:null}")
    private String retry;
    // 天润语音 重试间隔
    @Value("${tr.webcall.retryInterval:null}")
    private String retryInterval;
    // 天润语音 重试间隔
    @Value("${tr.webcall.timeout:null}")
    private String timeout;
    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private SysDeptTokenMapper sysDeptTokenMapper;

    @Override
    public AjaxResult webCall(CrmWebCallVO crmWebCallVO) {
        String result = null;
        String telTemp = null;
        try {
            String[] tels = crmWebCallVO.getTel().split(",");
            if(tels.length > 1){
                telTemp = tels[0];
            }else {
                telTemp = crmWebCallVO.getTel();
            }
            // 根据规则 一天内 某个手机号通知不能超过配置的次数
            String key= String.format(RedisKeyConstants.WEBCALL_TEL_LIMIT_COUNT, DateUtil.now(), telTemp);
            Long increment = redisTemplate.opsForValue().increment(key, 1);
            if (increment == 1L) {
                redisTemplate.expire(key, 2, TimeUnit.DAYS);
            }
            if((increment -1) >= Long.valueOf(webcallLimitCount)){
                String msg = telTemp + "号码,已超过每日限呼次数";
                return AjaxResult.error(msg);
            }

            // 1、根据部门ID 获取天润token和企业ID等信息
            SysDeptToken sysDeptToken = new SysDeptToken();
            sysDeptToken.setDeptId(crmWebCallVO.getDeptId());
            List<SysDeptToken> sysDeptTokens = sysDeptTokenMapper.selectSysDeptTokenList(sysDeptToken);
            if (sysDeptTokens == null) {
                return AjaxResult.error("根据部门ID为获取到Token信息");
            }
            SysDeptToken deptToken = sysDeptTokens.get(0);

            // 2、组装参数调用天润语音通知接口

            String webCallURL = this.connectURL(crmWebCallVO, deptToken);
            log.info("webCallURL = {}", webCallURL);
            // 3、远程调用天润接口
            result = HttpUtil.get(webCallURL);

            //4、返回调用结果
            if (StringUtils.isNotEmpty(result)) {
                JSONObject resObject = JSONObject.parseObject(result);
                // result    Int	0 成功, -1 失败
                if (Objects.nonNull(resObject) && resObject.getIntValue("result") == 0) {
                    return AjaxResult.success(resObject);
                }
            }
        } catch (Exception e) {
            log.error("ICrmWebCallServiceImpl.webcll 出现异常 Exception = {} ", e);
        }
        return AjaxResult.error("操作失败",JSONObject.parseObject(result));
    }

    /**
     * 拼接天润语音通知URL
     *
     * @param crmWebCallVO
     * @param deptToken
     * @return
     */
    @SuppressWarnings("all")
    private String connectURL(CrmWebCallVO crmWebCallVO, SysDeptToken deptToken) {
        long timestamp = new Date().getTime() / 1000;

        String recordUrl = String.format(CrmConstants.TR_WEB_CALL_URL, region, version);
        StringBuilder sb = new StringBuilder();
        sb.append("?");
        sb.append("validateType=2");
        sb.append("&enterpriseId=" + deptToken.getEnterpriseId());
        sb.append("&timestamp=" + timestamp);
        sb.append("&tel=" + crmWebCallVO.getTel());
        // 呼叫客户超时时间 说明：参数取值范围 0<=timeout<=60；不传入，默认30(单位:s)
        sb.append("&timeout=" + (StringUtils.isEmpty(timeout)?60:timeout));
        if (StringUtils.isNotEmpty(crmWebCallVO.getClid())) {
            sb.append("&clid=" + crmWebCallVO.getClid());
        }
        if (StringUtils.isNotEmpty(retry)) {
            sb.append("&retry=" + retry);
        }
        if (StringUtils.isNotEmpty(retryInterval)) {
            sb.append("&retryInterval=" + retryInterval);
        }
        if (crmWebCallVO.getIvrId() != null) {
            sb.append("&ivrId=" + crmWebCallVO.getIvrId());
        }
        if(crmWebCallVO.getFileId() != null){
            sb.append("&paramNames=" + "fileId");
            sb.append("&paramTypes=" + "1"); // 1 代表普通参数
            sb.append("&fileId=" + crmWebCallVO.getFileId());
        }
        sb.append("&sign=" + Md5Utils.hash(deptToken.getEnterpriseId() + timestamp + deptToken.getTrLoginToken()));
        return recordUrl.concat(sb.toString());
    }
}
